package com.xxxx.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.seckill.VO.GoodsVO;
import com.xxxx.seckill.VO.OrderDetailVO;
import com.xxxx.seckill.VO.ResponseBeanEnum;
import com.xxxx.seckill.exception.GlobalException;
import com.xxxx.seckill.mapper.OrderMapper;
import com.xxxx.seckill.pojo.Order;
import com.xxxx.seckill.pojo.SeckillGoods;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.service.ISeckillGoodsService;
import com.xxxx.seckill.service.ISeckillOrderService;
import com.xxxx.seckill.utils.MD5Util;
import com.xxxx.seckill.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2024-04-06
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 功能描述：秒杀
     *
     * @param user  :
     * @param goods :
     * @return :
     */
    @Transactional // 事务注解
    @Override
    public Order seckill(User user, GoodsVO goods) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 秒杀商品表减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>()
                .eq("goods_id", goods.getId())
        );
        seckillGoods.setSeckillStock(seckillGoods.getSeckillStock() - 1);
        // seckillGoodsService.updateById(seckillGoods);

        // 这种写法可以保证 seckill_stock 非负，但无法保证订单数不超额
/*        boolean seckillGoodsResult = seckillGoodsService.update(
                new UpdateWrapper<SeckillGoods>()
                        .set("seckill_stock", seckillGoods.getSeckillStock())
                        .eq("goods_id", goods.getId())
                        .gt("seckill_stock", 0)
        );*/

        // 使用 SQL 语句直接减库存，这种做法比较好
        boolean seckillGoodsResult = seckillGoodsService.update(
                new UpdateWrapper<SeckillGoods>()
                        .setSql("seckill_stock = seckill_stock - 1")
                        .eq("goods_id", goods.getId())
                        .gt("seckill_stock", 0)
        );

/*        // 根据更新结果判断是否要创建订单
        if (!seckillGoodsResult) {
            return null;
        }*/
        if (seckillGoods.getSeckillStock() < 1) {
            // 判断是否还有库存
            valueOperations.set("out_of_stock:" + goods.getId(), "0");
            return null;
        }
        // 生成订单
        Order order = new Order();
        // order.setId(); // 自动生成的，不用管
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddressId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0); // 未支付
        order.setCreateTime(new Date());
        // order.setPayTime(); // 未支付
        orderMapper.insert(order);

        // 生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        // seckillOrder.setId(); // 自动生成的，不用管
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId()); // 插入后会自动返回主键
        seckillOrder.setGoodsId(goods.getId());
        seckillOrderService.save(seckillOrder);
        valueOperations.set("seckill_order:" + user.getId() + ":" + goods.getId(), seckillOrder);

        // 返回订单
        return order;
    }

    @Override
    public OrderDetailVO detail(Long orderId) {
        if (null == orderId) {
            throw new GlobalException(ResponseBeanEnum.ORDER_NOT_EXISTS);
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(order.getGoodsId());
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setOrder(order);
        orderDetailVO.setGoodsVO(goodsVO);
        return orderDetailVO;
    }

    /**
     * 功能描述：获取秒杀地址
     *
     * @param user    :
     * @param goodsId :
     * @return :
     */
    @Override
    public String createSeckillPathFragment(User user, Long goodsId) {
        String fragment = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("seckill_path_fragment:" + user.getId() + ":" + goodsId, fragment, 60, TimeUnit.SECONDS);
        return fragment;
    }

    /**
     * 功能描述：校验秒杀地址
     *
     * @param user    :
     * @param goodsId :
     * @return :
     */
    @Override
    public boolean checkFragment(User user, Long goodsId, String fragmentClient) {
        if (null == goodsId || goodsId <= 0 || !StringUtils.hasText(fragmentClient)) { // 外面已经判断过 user 是否为空了，所以这里删掉了
            return false;
        }
        String fragmentServer = (String) redisTemplate.opsForValue().get("seckill_path_fragment:" + user.getId() + ":" + goodsId);
        return Objects.equals(fragmentServer, fragmentClient);
    }

    /**
     * 功能描述：校验验证码
     *
     * @param user          :
     * @param goodsId       :
     * @param captchaClient :
     * @return :
     */
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captchaClient) {
        if (null == goodsId || goodsId <= 0 || !StringUtils.hasText(captchaClient)) {
            return false;
        }
        String captchaServer = (String) redisTemplate.opsForValue().get("seckill_captcha:" + user.getId() + ":" + goodsId);
        return Objects.equals(captchaServer, captchaClient);
    }
}
